package com.leadbank.bigdata.es.core;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created by hp on 2017/4/27.
 */
public class LeadbankPropertyPlaceholder extends PropertyPlaceholderConfigurer {

    //static method for accessing context properties
    public String getProperty(String name) {
        return String.valueOf(properties.get(name));
    }

    private String systemId;
    private String configHome;
    private Properties properties;

    public LeadbankPropertyPlaceholder() {
    }

    public String getConfigHome() {
        return this.configHome;
    }

    public void setConfigHome(String configHome) {
        this.configHome = configHome;
    }

    protected Properties loadProperties(String systemId) throws IOException {
        configHome = configHome + "/" + systemId;
        File configDir = new File(configHome);
        if(!configDir.exists()) {
            throw new RuntimeException("Not found the configDir=[" + configHome + "].");
        } else {
            Properties envProps = new Properties();
            //查找目录下面的所有.properties文件
            if(configDir.isDirectory()) {
                File[] tempList = configDir.listFiles();
                for(File tempFile : tempList) {
                    //后去后缀
                    String fileSuffix = tempFile.getName().substring(tempFile.getName().lastIndexOf(".")+1);
                    if("properties".equals(fileSuffix)) {
                        envProps.load(new FileInputStream(tempFile));
                    }
                }

            }
            return envProps;
        }
    }

    public Properties getProperties() {
        return this.properties;
    }

    public String getSystemId() {
        return this.systemId;
    }

    public void setSystemId(String systemId) {
        this.systemId = systemId;
        try {
            this.properties = this.loadProperties(systemId);
        } catch (Exception ex) {
            throw new RuntimeException("Input systemId file error =[" + systemId + "].");
        }
        super.setProperties(this.properties);
    }
}
